简体   繁体   中英

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

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;

});

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 .

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