4

我试过了:

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

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

    }
}

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

但是在这两种情况下:

myModelInstance.func(); //object has no method func

我宁愿不使用_.bindAll().

我已经编辑了上面的代码以表明我正在尝试将 func 绑定到一个模型。模型在添加到集合时被初始化:所有模型同时触发初始化,我只想将 func 绑定到其中一个。

4

4 回答 4

14

有什么理由不做显而易见的事吗?

Model = Backbone.Model.extend({
  func: function() {
  },
})
于 2013-08-20T15:46:09.360 回答
3

在块中分配func为模型的属性。if

var Model = Backbone.Model.extend({
  initialize:function() {
    if (this.get('id') === 1) {
      this.func = function() {
          // your logic here
      };               
      this.on('func',this.func,this);
    }
  }
});
于 2013-08-20T16:49:48.370 回答
1

静态方法应该在 .extend 调用中的第二个字典上声明:

SomeModel = Backbone.Model.extend({
  initialize: function(){}
},{
  someStaticFunction: function(){
      //do something
  } 
});

http://danielarandaochoa.com/backboneexamples/blog/2013/11/13/declaring-static-methods-with-backbone-js/

于 2015-04-28T17:55:04.967 回答
0

尝试这个:

SomeModel = Backbone.Model.extend({
  initialize: function(){},
  someFunction: function(){
      //do something
  } 
});

和这个:

var model = new SomeModel();
model.someFunction();
于 2013-08-20T15:44:46.713 回答