骨干呼叫模型功能

Backbone call model function

本文关键字:功能 模型 呼叫      更新时间:2023-09-26

我有一个集合,从这个集合中我选择了一个模型。在这个模型中,我之前定义了一个函数。如何调用从集合中选择的模型的这个函数?

我调用模型函数(但未定义):

 var SingleHomePostView = Backbone.View.extend({
    tagName: "li",

    template: Handlebars.compile(template),

    events: {
        "click #retweet": "retweet",
      },

    initialize: function () {
        // console.log(this.model);
     this.model.bind("change", this.render, this);
     this.model.bind("destroy", this.close, this);
    },
    render: function (eventName) {
      var ad = this.model.toJSON();
      ad.cid = this.model.cid;
      $(this.el).html(this.template(ad));

      return this;
    },

    retweet: function () {//Here----------
            console.log(this.model);// is well defined
        console.log("retweet");
        console.log(this.model.reTweet()); //here I try to call model function
      },


  });

,这是模型:

      var Tweet = Backbone.Model.extend({


 reTweet: function(){
     var params = {
                user_id: 11265832,
                //screen_name:"brad"
                page:1,
                count:2,
            };

            cb.__call(
                "statuses_userTimeline",
                params,
                function (reply) {
                //gestire rate limit error 429
                 console.log(reply);
                // return reply;
                }
            );


 }

  });

这是调用先前视图的主视图。它迭代集合并将模型传递给视图。

 loadResults: function (eventName) {
        //this.showSpinner();
        console.log("homepostview"+this.page);
         this.isLoading === true;
            //console.log(this.IntegratedCollection);
            _.each(this.IntegratedCollection.last(this.IntegratedCollection.length).reverse(), function(model){
                 $(this.el).append(new SingleHomePostView({
                     model: model
                   }).render().el);

            },this);
            this.isLoading === false;;

          return this;

    },

似乎您的集合应该指定模型类型。查看文档获取更多信息

更新:

来源:

var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId('c');
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
};

要将您的模型关联到一个集合-该集合不是由集合通过fetch创建的-只需在创建它时将集合传递给模型(假设是这样)。Collection是实际的Collection实例):

new Model({collection: this.collection})