【问题标题】:View did not update in Backbone with text! plug-in视图没有在 Backbone 中用文本更新!插入
【发布时间】:2013-10-09 15:36:42
【问题描述】:

我刚从 Backbone.js 开始。现在我正在尝试将项目添加到 localStorage 中商店的购物车。这是我的看法:

define(["jquery" ,
  "underscore" ,
  "backbone" ,
  "text!templates/Cart/itemtemplate.html",
  "cart",
  "script"
],function($ , _ , Backbone , ItemTemplate, Cart , Script){

  var items = deserializeJSONToObj(localStorage.getItem("Cart"));
  var myCart = new Cart();
  var newItem = {
    "ID" : 348,
    "ItemCode" : "0352862925041",
    "PartNumber" : ""
    };

  if (!(items instanceof Array)) items = [];

  var promotionItem = _.template(ItemTemplate,{});

  var HomeView = Backbone.View.extend({
     initialize: function() {
          myCart.updateQtyLabel("qtyCart");
          $("#containernewpromotion").html(promotionItem);
     },
     el: '.addToCart-form',
     events : {
         "click #addToCart" :  function(){
             myCart.addToCart(newItem);
             myCart.updateQtyLabel("qtyCart");
             $("#containernewpromotion").html(promotionItem);
          }
     },
     render : function(){
        $("#containernewpromotion").html(promotionItem);
     }
  });
 return HomeView;

当我点击添加到购物车按钮时,商品数量标签updateQtyLabel() 功能正在运行,但内容 html 不会随着从 localStorage 获取的新内容而更新。

感谢您的任何指点。

【问题讨论】:

    标签: javascript jquery backbone.js requirejs


    【解决方案1】:

    您使用var promotionItem = _.template(ItemTemplate,{});准备您的模板
    通过传递第二个参数{},您可以强制对变量进行插值,然后promotionItem 是一个固定字符串,并且在数据更新时不会改变。

    你可能想做的是:

    • 准备一个编译好的模板:

      var promotionItem = _.template(ItemTemplate);
      
    • 获取更新的 HTML 内容:

      var html = promotionItem(myCart.toJSON());
      
    • 将其注入您的元素中:

      this.$el.html(html);
      // in your case, $("#containernewpromotion").html(html);
      // but I'm really not fond of fixed DOM elements in modules
      

    【讨论】:

    • 从未想过这是问题所在。我只是从promotionItem 中省略了{},就像您在第一个解决方案中指出的那样。它正在工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多