如何向骨干模型添加自定义方法?

4 backbone.js marionette

我试过了:

initialize: function() {
    if (this.get("id") == "modelOfInterest") {

        var func = function() {
           //do some stuff with the model
         }
         _.bind(func, this)

    }
}
Run Code Online (Sandbox Code Playgroud)

initialize: function() {
    if (this.get("id") == "modelOfInterest") {
          var func = function() {
            //do some stuff with the model
          }
          this.on("func", func, this);
     }
}
Run Code Online (Sandbox Code Playgroud)

但是在这两种情况下:

myModelInstance.func(); //object has no method func
Run Code Online (Sandbox Code Playgroud)

我不想使用_.bindAll().

我编辑了上面的代码,表明我试图将func绑定到只有一个模型.将模型添加到集合时进行初始化:所有模型同时触发初始化,我只想将func绑定到其中一个模型.

Ste*_*mas 14

有什么理由不明白吗?

Model = Backbone.Model.extend({
  func: function() {
  },
})
Run Code Online (Sandbox Code Playgroud)