【问题标题】:Knockout JS building a list of itemsKnockout JS 构建项目列表
【发布时间】:2012-05-21 18:37:12
【问题描述】:

我要做的是从其他更大的可用项目列表中建立一个项目列表(对于上下文,请考虑指定某种类型产品的成分)。当谈到淘汰赛时,我仍然很年轻,我想知道我是否遗漏了什么,因为我目前使用的解决方案感觉不对。我有几个非常标准的模板,并且正在对我的视图模型上的两个可观察数组使用 foreach 绑定(一个用于可用成分列表,一个用于产品的选定成分列表)。

<div data-bind="template: {name:'ingredientTypeTemplate', foreach: ingredientTypes}"></div>

<div data-bind="template: {name:'selectedIngredientTypeTemplate', foreach: selectedIngredientTypes}"></div>

<script>

var productTypeViewModel = {

    ingredientTypes: ko.observableArray([]),
    selectedIngredientTypes: ko.observableArray([]),

    addIngredient: function () {
        productTypeViewModel.ingredientTypes.remove(this);
        productTypeViewModel.selectedIngredientTypes.push(this);
    },

    removeIngredient: function () {
        productTypeViewModel.selectedIngredientTypes.remove(this);
        productTypeViewModel.ingredientTypes.push(this);
    },
};

$(document).ready(function () {

    $.getJSON("/IngredientType/Index")
            .success(function (data) {
                productTypeViewModel.ingredientTypes($.parseJSON(data));
            })
            .error(function () { alert("error"); });

    ko.applyBindings(productTypeViewModel);
});

</script>

<script type="text/x-jquery-tmpl" id="ingredientTypeTemplate">
    <div>
        <span>${Name}</span>
        <a href='#' data-bind="click: productTypeViewModel.addIngredient">Add</a>
    </div>
</script>

这是完成我想要对 Knockout 做的事情的最佳方式吗?感觉有些不对劲,虽然我不太确定是什么。我确实有一个单独的 VM 定义,它有一个 add 函数。可观察到的成分类型将使用该类型的一组 VM 进行初始化,然后模板仅在其上使用 data-bind“click: add”,但我不喜欢从这个虚拟机与主 VM 通信处理点击。

基本上,我只想说明我所做的是标准方法还是有更好(更适合 Knockout)的方法。

【问题讨论】:

    标签: javascript design-patterns mvvm knockout.js


    【解决方案1】:

    我认为您的方法是完全有效的,并且是我在其他淘汰赛示例中看到的。例如,从 Ryan Niemeyer 的 drag and drop plugin 的 v1 中,您可以找到与您正在执行的操作非常相似的以下代码 sn-p:

    if (position >= 0) {
        originalParent.remove(item);
        newParent.splice(position, 0, item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多