読者です 読者をやめる 読者になる 読者になる

素人がプログラミングを勉強していたブログ

プログラミング、セキュリティ、英語、Webなどのブログ since 2008

連絡先: すかいぷ:javascripter_  か javascripter あっと tsukkun.net skypeのほうがいいです

liveなquerySelectorAll

javascript

追記:いまいちだったので書き直し。

var liveQuery = function(){
  document.addEventListener("DOMSubtreeModified",update,false);
  var queries = {};
  function liveQuery(selector){
    if(!(this instanceof liveQuery)) return new liveQuery(selector);
    this.toString = function() "[" + selector + "]";
    if(this in queries) return queries[this].list;
    Array.prototype.push.apply(this,Array.slice(document.querySelectorAll(selector)));
    queries[this] = {selector:selector,list:this};
    return this;
  }
  liveQuery.prototype.item = function(n){
    return this[n] || null;
  };
  liveQuery.prototype.detach = function(){
    return delete queries[this];
  };
  function update(){
    for each(var {selector,list} in queries){
      var elems = document.querySelectorAll(selector);
      if(list.length < elems.length)
        for(var i = list.length;i < elems.length;i++)
          delete list[i];
      for(var i = 0;i < elems.length;i++)
        list[i] = elems[i];
      list.length = elems.length;
    }
  }
  return liveQuery;
}();

var liveLinks = liveQuery("a");
console.log(liveLinks[0],liveLinks.length);
liveLinks[0].parentNode.removeChild(liveLinks[0]);
console.log(liveLinks[0],liveLinks.length);
liveLinks.detach();

追記ここまで。

var liveQuery = function() {
  document.addEventListener("DOMSubtreeModified", mutain, false);
  var queries = [];
  function liveNodeList(list) {
    for (var i = 0; i < list.length; i++) this[i] = list[i];
    this.length = list.length;
    return this;
  }
  liveNodeList.prototype.item = function(n) {
    return this[n] || null;
  }
  function mutain() {
    queries.forEach(function({
      selector,
      list
    }) {
      var newList = document.querySelectorAll(selector),
      length = list.length;
      Array.forEach(newList,
      function(elem) {
        Array.prototype.unshift.call(list, elem);
      });
      for (var i = length; i < list.length; i++) delete list[i];
      list.length = length;
    });
  }
  return function liveQuery(query) {
    var list = new liveNodeList(document.querySelectorAll(query));
    queries.push({
      selector: query,
      list: list
    });
    return list;
  }
} ();

var liveLinks = liveQuery("a");
console.log(liveLinks[0],liveLinks.length);
liveLinks[0].parentNode.removeChild(liveLinks[0]);
console.log(liveLinks[0],liveLinks.length);