0

dom への変更 (属性、テキスト、html、追加、削除など) を認識できる jQuery オブジェクトへのノックアウト バインディングを作成しようとしています。

ko.bindingHandlers.jqHtml =
  init: (element, valueAccessor) ->
    $(element).preMutate (options, el) ->
      if ko.isObservable valueAccessor()
        valueAccessor().valueWillMutate()
    $(element).onMutate _.debounce (argsCollection) =>
      @argsCollection = argsCollection
      if ko.isObservable valueAccessor()
        valueAccessor().valueHasMutated()
    , 100

  update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
    content = valueAccessor()
    $(element).children().each( (i,el) -> ko.cleanNode(el) )
    if _.difference($(element).children().get(), content.get()).length > 0 || _.difference(content.get(),$(element).children().get()).length > 0
      $(element).children().peek().detach().unpeek()
      $(element).peek().append(content).unpeek()
    ko.applyBindingsToDescendants(viewModel, element)

進行中のjsFiddleがあります

jsfiddle によって明らかにされた問題は、jquery が dom 内の重複を追跡せず、代わりに要素を移動することです。したがって、同じ jq 要素に複数のバインディングがある場合、jQuery はそれを 1 つのデータ バインディングにしか配置できません。元のjquery要素を保持し、その要素のコピーを配布するjqObservableを作成する方法があるかもしれないと考えています。そして、onMutate が通知を受けるたびに、それらの各コピーを更新します。もちろん、インセプション ブロッカー (既にバインドされている要素の下にある同じ要素へのデータ バインディング) が必要です。私が考えることができる1つの問題は、どのサブスクリプションがオブザーバブルを呼び出して、jquery要素のどのコピーを返すかを知ることで、間違ったコピーを返さないようにし、バインド解除/サブスクライブ解除された要素を破棄することを知っていることです。私も' jquery コピーの 1 つが変更されたときに、残りの jquery コピーを更新する必要があります。ところで、jQuery 関数の外部で変更されてもかまいません。このプラグインの要素に対して jQuery 関数のみを呼び出す必要があります。

どんな提案でも大いに義務付けられます。

PS

OnMutate は私自身のカスタム jQuery プラグインです

私はもともと変更イベントをサブスクライブしようとしていましたが、それは入力以外には機能しませんでした。サブツリーの変更のためのトップレベルのサブスクライブはなく、最も近いものは、html の違いをチェックするために毎秒更新していました。別のオプションは、スタック オーバーフローで見た別のプラグイン、jollytoad のミューテーション イベントでした。

ただし、いくつかの関数でしか機能しませんでしたが、必要なすべての要素のコールバックを作成するというアイデアが得られたので、この関数を作成して、必要な数の jQuery 関数のコールバックの作成を自動化しました。プラグイン。以下に作成しました。

(($, window) ->
  hasArgs = () -> arguments.length > 0
  noArgs = () -> arguments.length == 0
  class DomCallbacks
    ###*
     * Defines the jQuery functions to create callbacks for, and which type of callback they contain
     * @type {defaults}
     *   @properties {array of jQuery function names, and test to determine if the callback 
     *   should be run based on input to the jQuery function, passed the same arguments that the jQuery
     *   function is}
    ###
    defaults:
      Mutate: 
        jqfuncs: ["addClass","append","appendTo","attr","clone","css","detach","empty","hasClass","height","html","innerHeight","innerWidth","insertAfter","insertBefore","offset","outerHeight","outerWidth","position","prepend","prependTo","prop","remove","removeAttr","removeClass","removeProp","replaceAll","replaceWith","scrollLeft","scrollTop","text","toggleClass","unwrap","val","width","wrap","wrapAll","wrapInner"]
        defaultCheck: hasArgs
      Look: 
        jqfuncs:["addClass","after",'append',"appendTo","attr","before","clone","css","detach","empty","hasClass","height","html","innerHeight","innerWidth","insertAfter","insertBefore","offset","outerHeight","outerWidth","position","prepend","prependTo","prop","remove","removeAttr","removeClass","removeProp","replaceAll","replaceWith","scrollLeft","scrollTop","text","toggleClass","unwrap","val","width","wrap","wrapAll","wrapInner"]
        defaultCheck: noArgs

    constructor: (options) ->
      @categories = $.extend({}, @defaults, options)

    originals: {} 

    ###*
     * Creates a function in jQuery's function object by replacing the name with a wrapper function
     * and then calling the original function, and has the new function call each category of callback
     * for the starting element and it's parents
     * @param {string} name       the name/key of the function being replaced
     * @param {string} categories the type of callback that the function should notify
    ###
    addCallback: (name, categories) ->
      pairs = (obj) ->
        pairs = []
        for key of obj 
          if (hasOwnProperty.call(obj, key))
            pairs.push([key, obj[key]])
        pairs

      if !@originals[name]?
        @originals[name] = $.fn[name]
      _this = @

      categories = $.grep pairs(categories), (pair) ->
        $.grep(pair[1].jqfuncs, (val) -> val.name == name || val == name).length > 0
      ###*
       * The actual wrapper function being created
       * @return {object} returns the original functions return
      ###
      $.fn[name] =  () ->
        options = {args: arguments}
        ittr = []
        if !$.fn[name].peek          
          ittrArray = for category in categories
            key = category[0]
            val = category[1]
            funcs = ($.grep(val.jqfuncs, (checking) -> checking.name == name || checking == name)).slice(0,1)[0].check
            {key:key, val: val ,funcs:funcs}

          for ittr in ittrArray
            if !ittr.funcs?
              ittr.funcs = ittr.val.defaultCheck
            if !ittr.funcs? or ittr.funcs.apply(@,arguments)
              @["pre"+ittr.key](null, options)
              @parents()["pre"+ittr.key](null, options)

        funcRet = _this.originals[name].apply(@, arguments)
        options.funcRet = funcRet

        if !$.fn[name].peek
          for ittr in ittrArray
            if !ittr.funcs?
              ittr.funcs = ittr.val.defaultCheck
            if !ittr.funcs? or ittr.funcs.apply(@,arguments)
              @["on"+ittr.key](null, options)
              @parents()["on"+ittr.key](null, options)

        funcRet

      $.fn[name].peek = false

    ###*
     * restores the original function to it's property in the jQuery function object
     * @param  {string} name key used to find function to restore
     * @return {[type]}      [description]
    ###
    removeCallback: (name) ->
      if @originals[name]?
        $.fn[name] = @originals[name]
        delete @originals[name]  

  ###*
   * Creates a jQuery plugin capable of subscribing to and calling callbacks
   * for each node
   * @param  {string} precedence names the function to run before or after the subscripton function
   * @param  {string} category   the name of the type of
   * @return {function}          returns the function capable of setting and running callbacks for individual elements
  ###
  createCallbackPlugin = (precedence, category) ->
    ###*
     * A jQuery plugin which creates a sets callbacks for elements and calls them if none are passed in
     * @param  {function} callback the callback to be set (optional)
     * @param  {object}   options  options to be sent to the callback, set by the trigger function
     * @return {jQuery}            returns jQuery object for chaining
    ###
    return (callback, options) ->
      @each (i, el)  ->
        if callback?
          if !el['domCallbacks']?
            el['domCallbacks'] = {}
          if !el['domCallbacks']['_'+precedence+category]?
            el['domCallbacks']['_'+precedence+category] = []
          el['domCallbacks']['_'+precedence+category].push callback
        else
          if el['domCallbacks']? && el['domCallbacks']['_'+precedence+category]?
            for cb in el['domCallbacks']['_'+precedence+category]
              cb(options, el)
        @
      @

  domCallbacks = new DomCallbacks()

  ###*
   * This creates each function inside of jQuery capable of setting and running callbacks on
   * individual elements.
   * @param  {[type]} options [description]
   * @return {[type]}         [description]
  ###
  $.extend createDomCallbacks: (options) ->
    $.extend({}, domCallbacks.categories, options)
    categoryFunctions = {}
    for key, category of domCallbacks.categories
      categoryFunctions['pre'+key] = createCallbackPlugin('pre',key)
      categoryFunctions['on'+key] = createCallbackPlugin('on',key)
      $.extend $.fn, categoryFunctions
    for key, category of domCallbacks.categories
      for val in category.jqfuncs
        domCallbacks.addCallback( (if val.name then val.name else val) , domCallbacks.categories)

    ###*
     * removes any callbacks each element in the jquery object
     * @param  {object} options an object conatining keys for the type of callback to be removed (e.g. options = {Mutate: {}})
     * @return {[type]}         returns jquery object for chaining
    ###
    $.extend $.fn, removeDomCallbacks: (options) ->
      @each (i, el) ->
        if el['domCallbacks']?
          if !options?
            delete el['domCallbacks']
          for category of options
            delete el['domCallbacks']["_pre"+category]
            delete el['domCallbacks']["_on"+category]

        @
      @
    ###*
     * turns off all callbacks for performing actions without notifying up the dom
     * @return {jQuery} for chaining
    ###
    $.extend $.fn, peek: () ->
      for key,val of domCallbacks.originals
        $.fn[key].peek = true
      @each (i, el) ->
        @
      @

    ###*
     * turns off all callbacks for performing actions without notifying up the dom
     * @return {jQuery} for chaining
    ###
    $.extend $.fn, unpeek: () ->
      for key,val of domCallbacks.originals
        $.fn[key].peek = false
      @each (i, el) ->
        @
      @

) @jQuery, @
4

0 に答える 0