简体   繁体   中英

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.

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

You could just use a reference instead of a string

var Myview = Backbone.View.extend({
  events: {
    'click p': Utils.action
  },
});

plnkr

Or if you want to mix the util methods into the view class instead of relying on delegation you can do

var Myview = Backbone.View.extend({
  events: {
    'click p': 'action'
  },
});
Myview.prototype.action = Utils.action;

plnkr

The above will preserve the context as you can see in the plunker.

My preferred method if you plan to start pulling more logic out this way would be to look at a plugin that offers mixin functionality. Marionette has (amongst many other useful things) functionality for sharing behaviors between views. There are several other approaches as well that you can research by googling for "Backbone mixin".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM