如何以编程方式加载KnockoutJS组件

时间:2015-07-26 12:06:54

标签: javascript knockout.js knockout-3.0

我开始为select2创建一个名为“select-two”的ko组件,但我很快意识到,有时我需要在注册绑定后以编程方式创建组件时加载组件。

我尝试过添加一个新元素,但当然它不起作用,我猜它必须重新加入。

var sel2 = $("<select-two></select-two>") ;
$("#selectList").append(sel2) ; 

关于如何重新绑定整个视图模型有很多参考,但只有组件?我觉得这家伙有同样的问题: Load knockoutjs component using javascript

仅供参考,这是组件代码:

define([
'knockout',
'text!./select-two.html',
'select2'
], function (ko,  templateMarkup, select2) {
ko.components.register('select-two', {
    viewModel: function(params) {

        var placeholder = params.placeholder;
        var value = params.value;

        ko.bindingHandlers.select2 = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                $(element).select2({
                        placeholder: placeholder,
                        minimumInputLength: 1,
                        ajax: {
                            url: function (term, page) {
                                return '/models/autores/busqueda/' + term['term']
                            },
                            dataType: 'json',
                            quietMillis: 200,
                            processResults: function (data) {
                                return data;
                            }
                        },
                        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
                    }
                ).on('change', function(event){
                        ds = $(element).select2('data')[0] ;

                        value['id'](ds['id']) ;
                        value['text'](ds['text']) ;
                    });
            }
        };
        return{
        }
    },
    template: templateMarkup
});
});

我的模板:

<link rel="stylesheet" href="/assets/js/vendor/select2/dist/css/select2.css" />
<select class="form-control" data-bind="select2"></select>

以及如何加载它:

<select-two id="authorSelect" params="placeholder: 'Pick an Author', value: autorSelectData" ></select-two>

ko.bindingHandlers.select2 = {
   init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
      var params = ko.unwrap(valueAccessor());
      $(element).select2({
         placeholder: params.placeholder,
         minimumInputLength: 1,
         data: params.data
       }).on('select2:select', function(e) { 
        params.value(e.params.data.text);
       });
      $(element).select2('val', params.value); // set initial value
   }
};

ko.components.register('select-two', {
  viewModel: function(params) {
    this.value = params.value;
    this.data = params.data;
  },
  template: '<select class="form-control" style="width: 200px;" data-bind="select2: ' + 
            '{placeholder: \'Pick a fruit\', value: value, data: data}">' +
            '</select>'
});

var app = {
  newSelect: function(){
    var cont = $("<p></p>") ; 
    var sel2 = $("<select-two></select-two>") ; 
    ko.applyBindings({}, sel2[0]) ;
    cont.append(sel2) ; 
    $("#select-list").append(cont) ; 
    
  },
  autorSelectData: ko.observable(null), 
  options: ['apple','pear','peach','mango','grape']
};

ko.applyBindings(app);
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
Just the binding: <select class="form-control" style="width: 200px;"
        data-bind="select2: {placeholder: 'Pick a fruit', value: autorSelectData, data: options}">
</select><br>
With component: <select-two params="value: autorSelectData, data: options"></select-two>

<p>Adding Selects</p>
<div id="select-list">
  
</div>

<input type="button" data-bind="click: newSelect()" value="New Select" id="new-select" />

1 个答案:

答案 0 :(得分:1)

  

我猜它必须被重新加入。

请记住,当您将重新绑定视为解决方案时,在99%的情况下,您应该重新考虑您的方法。

  

以编程方式创建组件。

如果您遵循MVVM / MVC指南,则永远不必执行此操作。所有数据模型/视图的结构都是预先定义的;只有他们的内容可以改变。

你不应该做什么?

  • 在组件内注册自定义绑定,这意味着每次创建组件实例时都会重新注册。
  • 在组件模板中链接样式表,这意味着每次创建组件实例时(而不是一次)都会加载样式表。
  • select2 docs展示时使用change事件,您必须使用select2:select

下面是你的代码的精简版本(例如,数据阵列而不是AJAX),展示了它如何与(1)绑定,以及(2)与encapsulatin组件一起工作。它仍然不起作用,如果是的话,什么不起作用?

ko.bindingHandlers.select2 = {
   init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
      var params = ko.unwrap(valueAccessor());
      $(element).select2({
         placeholder: params.placeholder,
         minimumInputLength: 1,
         data: params.data
       }).on('select2:select', function(e) { 
        params.value(e.params.data.text);
       });
      $(element).select2('val', params.value); // set initial value
   }
};

ko.components.register('select-two', {
  viewModel: function(params) {
    this.value = params.value;
    this.data = params.data;
  },
  template: '<select class="form-control" style="width: 200px;" data-bind="select2: ' + 
            '{placeholder: \'Pick a fruit\', value: value, data: data}">' +
            '</select>'
});

var app = {
  autorSelectData: ko.observable(null), 
  options: ['apple','pear','peach','mango','grape']
};

ko.applyBindings(app);
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
Just the binding: <select class="form-control" style="width: 200px;"
        data-bind="select2: {placeholder: 'Pick a fruit', value: autorSelectData, data: options}">
</select><br>
With component: <select-two params="value: autorSelectData, data: options"></select-two>