Search code examples
javascriptbackbone.js

Backbone.js and refactoring correctly


I'm new to backbone so forgive me if this is obvious. I wrote a function to change the value associated with a toggle switch to either true or false based on its position. I used this code in two different views and want to refactor it out.

I created a Utils object and attached the function as a method to that object. I then imported Utils into both views. Here is a bit of the code as I have it properly functioning now:

    var AddView = AbstractView.extend({
    template: "path/to/template.html",
    events: {
        "change .toggleBoolean" : "temp"
    },
    temp: function(e){
        Utils.toggleValue.call(this, e);
    }, ...

This works in both places as expected. However, I was hoping to replace "temp" in the events hash with the temp method. Any direction on how to properly do this would be greatly appreciated.


Solution

  • You can simply do this:

    var AddView = AbstractView.extend({
      template: "path/to/template.html",
      events: {
        "change .toggleBoolean" : Utils.toggleValue
      },
    

    Utils.toggleValue will be invoked in view's context.


    Here is the part of backbone code that deals with the event object:

    for (var key in events) {
       var method = events[key];
       if (!_.isFunction(method)) method = this[method];
       if (!method) continue;
       var match = key.match(delegateEventSplitter);
       this.delegate(match[1], match[2], _.bind(method, this));
     //-------------------------------------^ context is handled here
    }
    

    it checks whether value is a function, and binds the handler function context to view