2012-05-19 3 views
0

이 질문에 대한 정확한 설명이 확실하지 않지만 재정렬/이동할 수 있도록 이미지 배열을 처리하는 javascript 개체를 만들려고합니다. 그래서 기본적으로개체 자체에 대한 참조

function imgHandler(divname) { 
    this.imgDiv = divname; 
    this.img = Array("bigoldlizard.png","scarytiger.gif"); 
    this.update = function() { 
     var htmlstr = ""; 
     for(i=0; i<this.img.length; i++) { 

//This is the line in question: 
     htmlstr += "<img src=\"" + this.img[i] + "\" onclick=\"javascript:" + ??? + ".remove(" + i + ")\"/></span>"; 

     } 
     $("#" + this.imgDiv).html(htmlstr); 
    } 

    //remove an image from the array 
    this.remove = function(index) { 
     if (index >= 0 && index < this.img.length) { 
      this.img.splice(index, 1); 
      this.update(); 
      return true; 
     } 
     else 
      return false; 
    } 
} 

, 나는

+0

일부 HTML과 실제로 코드에서 기대하는 것을 게시하십시오. 어느 쪽이든 JQuery UI의 [Sortable] (http://jqueryui.com/demos/sortable/) 플러그인을 살펴볼 수있다. –

답변

3

대신 HTML 코드의 요소를 만들고을 유지하기 위해 클로저를 만들 ... 자신의 이름을 추가하거나 itsself을 참조 할 수 할 수 있도록 객체가 필요

this.update = function() { 
    var i, img; 
    for(i=0; i<this.img.length; i++) { 

     // closure for "this" and "i" 
     (function(t, i){ 

     img = $('<img/>', { src: this.img[i] }).click(function(){ 
      t.remove(i); 
     }); 

     })(this, i); 

     $("#" + this.imgDiv).append(img); 
    } 
    } 
+0

이 클로저는 지금까지 가장 깨끗한 솔루션입니다. –

+0

그 중 하나 또는 이벤트 데이터를 사용하십시오. –

+0

이벤트 데이터를 사용하는 것에 대해 자세히 설명 할 수 있습니까? – mavix

0

Guffa의 솔루션은 충분할 수 있지만 일반적으로 루프 내에서 클로저를 만들 수있는 좋은 생각이 아니다 : 루프 반복에서 변수, 이벤트 핸들러 코드는 변수를 사용할 수 있습니다.

// CALLBACK MANAGER MODULE BEGIN 
// Create a manager for creating callbacks. 
var callbackManager = (function() { 
    var win = window, 
     random = Math.random, 
     // Create a hash for us to save all callbacks on. 
     callbacks = {}, 
     // Generates the next unique ID for a callback. 
     nextId = (function() { 
      var next = 1; 

      return function() { 
       var n = next; 
       next += 1; 
       return n; 
      }; 
     }()), 
     // Generates the next valid callback name. 
     nextCallbackName = function (prefix) { 
      prefix = prefix || "___callback"; 
      return prefix + nextId(); 
     }; 

    // Save our hash of callbacks on the window object 
    // so we can get access to the callbacks globally. 
    win.callbacks = callbacks; 

    return { 
     // Creates a callback that will call the specified 
     // method on the 'thisObj'. Can specify optional arguments 
     // to have passed to the method call: 
     // 
     // callbackManager.makeMethodCallCallback(myObj, "welcome", "Alex"); 
     // 
     // The callback will be returned and saved so it can 
     // be accessed globally. 
     // 
     // Each callback will be a function with the following methods: 
     // getPath - Get the exported (i.e. global) path of the callback. 
     // dispose - Disposes the callback by nulling out all references 
     //  and removing it from global access. 
     // 
     // makeCallback(thisObj, methodName, ...) 
     makeMethodCallCallback: function (thisObj, methodName) { 
      var name = nextCallbackName(), 
       args = Array.prototype.slice.call(arguments, 2), 
       callback = function() { 
        if (thisObj && 
         typeof thisObj[methodName] === "function") { 
         return thisObj[methodName].apply(thisObj, args); 
        } 
       }; 

      callback.getPath = function() { 
       return "window.callbacks." + name; 
      }; 
      callback.dispose = function() { 
       thisObj = null; 
       callback = null; 
       args = []; 
       delete callbacks[name]; 
      }; 

      return callback; 
     }; 
    }; 
}()); 
// CALLBACK MANAGER MODULE END 

function imgHandler(divname) { 
    this.imgDiv = divname; 
    this.img = Array("bigoldlizard.png","scarytiger.gif"); 
    // Define an array of callbacks. 
    var callbacks = []; 

    this.update = function() { 
     var htmlstr = "", 
      // Declare a local variable for a callback. 
      callback; 

     for(i=0; i<this.img.length; i++) { 

     // Create a new callback and save it so we can dispose it when 
     // this image is removed. We also pass the index of the image. 
     callback = callbackManager.makeMethodCallCallback(this, "remove", i); 
     callbacks.push(callback); 
     // All callbacks have a getPath() method that will return 
     // the callback's exported (i.e. global) path, such as "window.callbacks.__callback92". 
     htmlstr += '<img src="' + this.img[i] + '" onclick="' + callback.getPath() + '(); return false;/></span>'; 

     } 
     $("#" + this.imgDiv).html(htmlstr); 
    } 

    //remove an image from the array 
    this.remove = function(index) { 
     if (index >= 0 && index < this.img.length) { 
      this.img.splice(index, 1); 
      this.update(); 

      // Dispose the callback associated to this image 
      // then tombstone it so that the order other callbacks 
      // will be maintained. 
      if (callbacks[index]) { 
       callbacks[index].dispose(); 
       // Tombstone the callback. 
       callbacks[index] = undefined; 
      } 

      return true; 
     } 
     else 
      return false; 
    } 
} 

Guffa의 기술이 하나가 비록 트릭을 수행해야합니다 나는 당신의 부분에 많은 리팩토링이 필요하고 좀 더 코드 임에도 불구하고 재사용 가능한 구성 요소를 제공하지 않는 다른 접근 방식을 가지고있다.

편집 : jQuery를 사용하고 있다는 것을 깨닫지 못했습니다. 가능하다면 onclick 속성보다 jQuery의 click() 이벤트 도우미를 사용하는 것이 좋습니다. 아마도 내 callbackManager과 Guffa의 접근 방식을 결합하여 두 가지 장점을 모두 제공 할 수 있습니다. <img> 요소를 만들고 jQuery의 click() 도우미를 사용하고 재사용 가능한 콜백 관리자 모듈을 사용합니다.