2012-03-01 5 views
5

저는 재사용 가능한 구성 요소를 프로젝트 용 jQuery 플러그인으로 만들고 있습니다. 저는 논리를 추상화 할 수 있고, 모든 상황 (선택자, 옵션 등)을 사례별로 주입 할 수있는 것을 좋아합니다.KnockoutJS로 재사용 가능한 구성 요소 만들기

이제 KnockoutJS를 사용하기 시작했으며 내부 논리에 Knockout을 사용하는 작은 jQuery 플러그인을 작성했습니다. 그것은 꽤 잘 작동하지만, 더 좋은 방법이 있는지 궁금합니다. 녹아웃 자체가 재사용 가능한 구성 요소를 만들기위한 패턴/규칙을 가지고 있습니까? 아니면이 패턴이 괜찮습니까?

예를 들어, 내가하는 일에 대한 아이디어를 제공하기에 충분해야합니다.

/*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)); 

답변

2

KO 구성 요소에 대한 github 프로젝트를 실행합니다. KO의 이전 버전을 사용하고 있으며 주요 개선 작업이 필요하지만 아이디어를 얻을 수는 있습니다. 기본적으로 모델 객체를 구성 및 데이터로 사용하는 사용자 정의 바인딩을 통해 모든 작업을 수행합니다.

나는 항상 이것을하기위한 더 좋은 방법을 찾고있다. 더 나은 방법을 생각해 내면 계속 알려주세요.

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

+0

매우 좋습니다. 그래서 "KO에 패턴/구성 요소 생성 규칙이 있습니까?"라는 대답은 기본적으로 없다고 생각합니다. –

+0

내가 아는 바 없다. 기능성을 맞춤 바인딩으로 옮기는 것이 하나의 패턴이라고 생각합니다. 이 점에 있어서는 상당히 제한적이지만, 다른 사람이 이에 대한 변형을 도출 할 수 있습니다. 넉 아웃 유효성 검사는 많은 작업을 수행 할 수있는 확장 기능을 제공하는 재사용 가능한 구성 요소입니다. – madcapnmckay

관련 문제