2012-03-01 14 views
5

He estado creando componentes reutilizables como complementos jQuery para proyectos desde hace algún tiempo. Me gusta poder abstraer la lógica e inyectar todo el contexto (selectores, opciones, etc.) caso por caso.Creación de componentes reutilizables con KnockoutJS

Ahora, estoy empezando a utilizar KnockoutJS, y he escrito un pequeño y agradable plugin jQuery que usa Knockout para su lógica interna. Funciona bastante bien, pero me pregunto si hay una mejor manera de hacerlo. ¿Knockout tiene un patrón/convención para crear componentes reutilizables, o este patrón está bien?

Aquí hay un ejemplo, debería ser suficiente para darle la idea de lo que estoy haciendo.

/*globals jQuery, knockout */ 
(function ($, ko) { 
    "use strict"; 
    $.fn.itemManager = function (options) { 
     // set up the plugin options 
     var opts = $.extend({}, $.fn.itemManager.defaultOptions, options), 
      $wrap = $(this), 
      templateUrl = '/path/to/template/dir/' + opts.templateName + '.html'; 

     // set up the KO viewmodel 
     function ItemManagerModel(items) { 
      var self = this; 

      self.items = ko.observableArray(items); 
      self.chosenItemId = ko.observable(); 
      self.chosenItemData = ko.observable(); 

      // generic method for navigating the Item hierarchy 
      self.find = function (array, id) { 
       /* ... */ 
      }; 

      /* bunch of other stuff... */ 

      self.goToItem(items[0]); 
     } 

     // this is where the whole thing starts... 
     $(opts.openTriggerSelector).click(function (e) { 
      e.preventDefault(); 

      // set the template html 
      $.get(templateUrl, function (data) { 
       $wrap.html(data); 
      }); 

      // initial load and binding of the data, in reality I have some more conditional stuff around this... 
      // there's probably a better way to do this, but I'll ask in a separate question :) 
      $.get(opts.getItemsServiceUrl, function (result) { 
       ko.applyBindings(new ItemManagerModel(result), document.getElementById($wrap.attr('id'))); 
       $wrap.data('bound', true); 
      }); 

      // opens the template, which now is bound to the data in a dialog 
      $wrap.dialog({ /* ... */ }); 

    // provide default plugin options 
    $.fn.itemManager.defaultOptions = { 
     getItemsServiceUrl: '/path/to/service', 
     openTriggerSelector: 'a', 
     templateName: 'Default' 
    }; 
} (jQuery, ko)); 

Respuesta

2

Ejecutar un proyecto github para componentes KO. Está usando una versión anterior de KO y se espera una renovación importante, pero es posible que puedas obtener algunas ideas. Básicamente lo hago a través de enlaces personalizados que toman objetos modelo como su configuración y datos.

Siempre estoy buscando una forma mejor de hacerlo. Mantenme informado si se te ocurre una mejor manera.

https://github.com/madcapnmckay/Knockout-UI

+0

Very cool. Así que supongo que la respuesta a "¿KO tiene patrones/convenciones para crear componentes" es básicamente no? –

+0

Ninguna que yo sepa. Supongo que el movimiento de la funcionalidad en enlaces personalizados es un patrón. Es bastante limitado en este sentido, pero bueno, alguien puede encontrar variaciones sobre esto. Knockout Validation es un componente reutilizable que proporciona extensores para hacer la mayor parte del trabajo. – madcapnmckay

Cuestiones relacionadas