require. how to pass a model to a view (backbone)

耗尽温柔 提交于 2019-12-24 21:16:36

问题


I'm using require.js with backbone. My question: is how do I fetch.() my model from within my view. What I have tried is below, however I get the error 'Campaign is undefined'. I think I'm very close:

Model:

define([
  'underscore',
  'backbone'
], function(_, Backbone) {

    var Campagin = Backbone.Model.extend({
       urlRoot: '/api/v1/campaign/'
    });

  return Campagin;

});

View:

define([
  'jquery',
  'underscore',
  'backbone',
  'views/RewardView',
  'views/FriendRewardView',
  'models/CampaginModel',
  'text!templates/backbone/portal/campaignTemplate.html'
], function($, _, Backbone, campaignTemplate){


   var CampaginView = Backbone.View.extend({
       el: '#campaign-panel',
        render: function(options) {
            if(options.id){

                var campaign = new Campagin({id: options.id});
                campaign.fetch({
                    success: function(campaign){
                        // We can only get the reward when the campaign reward url is returned.

                        var rewardview = new RewardView();
                        rewardview.render({reward_url: campaign.get('participant_reward')});


                        var friendview = new FriendRewardView();
                        friendview.render({reward_url: campaign.get('friend_reward')});


                        var template = _.template(campaignTemplate, {campaign: campaign});
                        this.$el.html(template);






                    }// end success
                }); // end fetch
            }// end if option.id
        } // end render function
    }); // end campagin view


  return CampaginView;

});

回答1:


In your View you are specifying an array of dependencies, which will be passed to the definition function as function arguments, listed in the same order as the order in the array. But you only declared 4 arguments: $ (jQuery), _ (underscore), Backbone and campaignTemplate(which is wrong because according your dependencies should be RewardView). So you have to declare properly your functions. For example:

define([
  'jquery',
  'underscore',
  'backbone',
  'views/RewardView',
  'views/FriendRewardView',
  'models/CampaginModel',
  'text!templates/backbone/portal/campaignTemplate.html'
], function($, _, Backbone, RewardView, FriendRewardView, Campagin, campaignTemplate){

   ...
}

Check the documentation of Require JS for more info.



来源:https://stackoverflow.com/questions/19903372/require-how-to-pass-a-model-to-a-view-backbone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!