简体   繁体   English

要求。 如何将模型传递到视图(主干)

[英]require. how to pass a model to a view (backbone)

I'm using require.js with backbone. 我正在将require.js与骨干网一起使用。 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 ). 但是您只声明了4个参数: $ (jQuery), _ (下划线), BackbonecampaignTemplate (这是错误的,因为根据您的依赖关系应该是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 . 有关更多信息,请参阅Require JS文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM