Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Grails 将主干集合传递到视图_Grails_Backbone.js_Handlebars.js - Fatal编程技术网

Grails 将主干集合传递到视图

Grails 将主干集合传递到视图,grails,backbone.js,handlebars.js,Grails,Backbone.js,Handlebars.js,我刚刚开始使用主干网/grails,我一直在努力找出如何让一切正常工作 我正在构建一个定价配置程序,其中用户从包含数量/定价/折扣数据的无线组a和无线组B中选择产品类型,并向后端进行ajax调用以获取更新的定价数据。我不想在前端公开我的定价算法,所以我想我应该使用主干网来处理我的ajax请求/模板 我不想完全依赖js来创建UI,因此在初始页面加载时,我将使用grails构建gsp视图。我注意到的唯一问题是,在初始页面加载时,我的gsp视图被我的把手模板所取代。我想这很好,除了它执行两个相同的查询

我刚刚开始使用主干网/grails,我一直在努力找出如何让一切正常工作

我正在构建一个定价配置程序,其中用户从包含数量/定价/折扣数据的无线组a和无线组B中选择产品类型,并向后端进行ajax调用以获取更新的定价数据。我不想在前端公开我的定价算法,所以我想我应该使用主干网来处理我的ajax请求/模板

我不想完全依赖js来创建UI,因此在初始页面加载时,我将使用grails构建gsp视图。我注意到的唯一问题是,在初始页面加载时,我的gsp视图被我的把手模板所取代。我想这很好,除了它执行两个相同的查询,这不是最优的

无论如何,我的代码似乎不起作用

<script id="priceTemplate" type="text/x-handlebars-template">
    <tr>
        <td><input type="radio" value="" name="quantity">{{quantity}}</td>
         <td class="price"><span>{{price}}</span></td>
        <td class="discount"><span>{{discount}}</span></td>
    </tr>
</script>

<asset:javascript src="bb_product/config.js"/>

<script>   
    var prices = new models.PriceList([],{productId:${productInstance.id}});
    var priceView = new PriceView({collection: prices});
    prices.fetch();     
</script>
查看

var PriceView = Backbone.View.extend({
    el: '#product-quantities',

    template: Handlebars.compile($("#priceTemplate").html()),

    initialize: function(){
        this.render();
    },

   render: function() {
       console.log('collection ' + this.collection.toJSON()) //comes back empty
       this.$el.html( this.template(this.collection.toJSON()));
   }

});
从url返回的json

[{"id":1,"quantity":10,"price":"10","discount":"10"},{"id":2,"quantity":50,"price":"20","discount"
:"10"}]
为了让它开始工作,我缺少什么来显示json对象中的所有项目


我也看到了这段代码,不确定它做什么
this.listenTo(this.collection,'reset',this.render)

看不到任何项目的原因是,在呈现视图之前,项目实际上不在集合中。请看这两行代码:

var priceView = new PriceView({collection: prices});
prices.fetch();
第一行呈现视图(因为您正在从
初始化
中调用
render
)。但是,此时,
prices
集合为空。然后,第二行从服务器获取数据并将其加载到集合中;但到那时,视图已经呈现

您发布的最后一行代码是解决此问题的关键:

this.listenTo(this.collection, 'reset', this.render);
通常,您会将其放入视图类中的
initialize
函数中。它所做的是“侦听”集合实例,当发生
reset
事件时,它将调用
this.render
函数。(当然,方法
this.listenTo
可以“侦听”其他对象中的其他事件;请参阅更多详细信息)

如果将该行添加到视图的
initialize
函数中,则每当集合上发生“reset”事件时,视图将重新呈现

但是,默认情况下,当集合中的所有模型都替换为另一组模型时,会发生“重置”事件,而在调用集合的
fetch
方法时,默认情况下不会发生这种情况(相反,集合将尝试“智能更新”)。要在使用
fetch
时强制重置集合,请将
{reset:true}
作为参数传递:

prices.fetch({reset: true});
prices.fetch({reset: true});