2009-11-30 6 views
0

다음 문제 :객체 참조 문제

jQuery로 작은 클립 보드를 만들고 싶습니다. $ (object) .data ('id', objectToStore)를 사용하여 javascript 객체의 데이터에 객체를 저장하려고 여러 번 시도했습니다. 거기에서 잘 작동하는 객체를 저장할 수 있습니다. 문제는 저장된 데이터를 삽입하려고하면 해당 객체에 대한 참조 만 가져옵니다. 그래서 하나의 사본을 편집 할 때 다른 사본도 변경됩니다. html 코드를 전역 변수에 복사 한 다음 저장된 코드를 개별적으로 삽입하는 방법이 필요합니다. 희망은 너희들이 내 문제를 이해! 고마워! 여기

코드 :

객체 객체이었다

/** 
    * Objectdefinition 
    */ 
Clipboard = { 

    //PROPERTIES 
     itemcount: 0,   
     maxItems:10,    

     //Templates 
     tplClipboard:"<div id='GUI_clipboard'><a href='' title='clear&nbsp;clipboard' id='GUI_clipboardClose' class='gritter-close'></a><ul></ul></div>", 
     tplItem:"<li><a href='' class='[[type]] clipboardItem' id='[[id]]'><span class='hidden'>[[text]]</span></a></li>", 
     tplItemHover:"<div class='GUI_clipboard_itemhover' style='width:[[offsetW]]px;height:[[offsetH]]px'><a href='' title='delete&nbsp;container' class='GUI_containerDelete'><span class='hidden'>Delete</span></a></div>", 

     //Clipboarditem 
     item:{ 
      id:null, 
      type:null, 
      content:'', 
      offsetWidth:0, 
      offsetHeight:0 
     }, 

    //FUNCTIONS 
     addItem:function(id,type,text,content,offsetH,offsetW){ 
      if(this.itemcount>=this.maxItems){ 
       return $.gritter.add({ 
        title:'Clipboard', 
        text:'You cannot store more than '+ this.maxItems +' Elements!', 
        image:'warning', 
       }); 
      } 


      var item = {}; 
       item.id=id, 
       item.type=type, 
       item.content=content, 
       item.offsetHeight=offsetH, 
       item.offsetWidth= offsetW; 


      this.verify(); 


      if (!this.checkRed(id)) { 


       this.itemcount++; 


       var tmp = this.tplItem; 


       tmp = this.str_replace(['[[type]]', '[[id]]', '[[text]]'], [type, id, text], tmp); 

       $('#GUI_clipboard ul').append(tmp); 
       var $item = $('a#'+id); 
       var number = this.itemcount; 
       $item.hide().fadeIn('slow',function(){ 

        Clipboard.redraw(); 
       }); 


       this.saveItem(item); 


       var config = { 
        over:function(){Clipboard.hoveringItem($('a',this))}, 
        out:function(){Clipboard.unhoveringItem($('a',this))}, 
        timeout:1 
       }; 
       $item.parent().hoverIntent(config); 


       $item.draggable({ 
        connectToSortable:'.column',       
        helper:'clone',          
        revert:'invalid',         
        cursor:'move',          //Cursor 
        start:function(){ 
         $('body').unbind('mouseover',Content.showContainerMenu); 
         $('body').unbind('mouseout',Content.hideContainerMenu); 
         $('#GUI_clipboard li').trigger('mouseout'); 
        }, 
        stop:function(){ 
         $('body').bind('mouseover',Content.showContainerMenu); 
         $('body').bind('mouseout',Content.hideContainerMenu); 
        } 
       }); 
      }else{ 

       $('#'+id,'#GUI_clipboard').effect("bounce", { times:3 }, 300); 
      } 
     }, 


     saveItem:function(item){    
      $(this).data(item.id,item); 
     }, 


     removeItem: function(id){ 
      $('#GUI_clipbaord').data(id,null); 
      $('a[id='+id+']','#GUI_clipboard').parent().slideUp('slow',function(){$(this).remove()}); 
      this.itemcount--; 

      if(this.itemcount==0)this.remove(); 
     }, 


     verify:function(){ 
      if($('#GUI_clipboard').length == 0){ 
       $('body').append(this.tplClipboard);      

       $('#GUI_clipboard')       
        .css({ 
         top:$(window).height()/2+'px'      
        }) 
        .animate({           
         left:0 
        }).children('.gritter-close').capture({cssClass:'GUI_clipboardClose'});  
      } 
     }, 


     checkRed:function(id){ 
      if($('a[id='+id+']').length==0)return false; 
      else return true; 
     }, 


     remove:function(){ 
      $('#GUI_clipboard').animate({            
       left:'-60px' 
      },function(){ 
       $(this).remove(); 
      }); 
      this.itemcount=0; 
     }, 


     hoveringItem:function(el){ 

      var item = $(this).data($(el).attr('id')), 
       content=item.content, 
       oH=item.offsetHeight, 
       oW=item.offsetWidth, 


      tmp = this.tplItemHover;     
      tmp = this.str_replace(['[[offsetW]]', '[[offsetH]]'], [oW,oH], tmp); 


      $(el).after(tmp); 
      var $element = $('.GUI_clipboard_itemhover').append(content).prepend("<div class='GUI_clipboardArrow'></div>"); 


      $element.position({ my: 'left center', at: 'right center', of: $(el),offset:'14 0',collision:'none fit'}); 
      $('.GUI_clipboardArrow',$element).position({ my: 'left center', at: 'right center', of: $(el),offset:'-2 0',collision:'none fit'}); 


      $('#'+item.id,'#GUI_clipboard').removeClass('borderContainer editable'); 


      $('a.GUI_containerDelete',$element).click(function(){ 
       Clipboard.removeItem($element.children('.container').attr('id')); 
       $element.fadeOut().remove(); 
      }).capture({cssClass:'GUI_clipboardItemClose'}); 

     }, 


     unhoveringItem:function(el){ 
      //Preview entfernen 
      $(el).next().remove(); 
     }, 


     redraw:function(){ 
      if(this.itemcount>1){ 
       $('#GUI_clipboard').animate({ 
        top: '-=20px'      
       }); 
      } 
     }, 


     str_replace: function(search, replace, subject, count) { 

      var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0, 
       f = [].concat(search), 
       r = [].concat(replace), 
       s = subject, 
       ra = r instanceof Array, sa = s instanceof Array; 
      s = [].concat(s); 
      if (count) { 
       this.window[count] = 0; 
       } 

      for (i=0, sl=s.length; i < sl; i++) { 
       if (s[i] === '') { 
        continue; 
       } 
       for (j=0, fl=f.length; j < fl; j++) { 
        temp = s[i]+''; 
        repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0]; 
        s[i] = (temp).split(f[j]).join(repl); 
        if (count && s[i] !== temp) { 
         this.window[count] += (temp.length-s[i].length)/f[j].length;} 
       } 
      } 
      return sa ? s : s[0]; 

     } 
} 

! 요소 위로 마우스를 가져 가면 Object가 내부 저장소에서 가져옵니다. 나는 콘텐츠 영역에 다음과 같이 객체를 삽입하고 때

var item = $(Clipboard).data($(ui.sender).attr('id')), 
         newItem = $.extend(true, {}, item); 
         content=newItem.content; 

한 다음 드래그 다시 contentarea에서 개체 (HTML 코드)를 삽입 할 클립 보드를 가져 사라지고의 미리보기에 삽입 클립 보드.

아이디어가 없습니다.

주세요!

답변

1

혼자서 해결책을 찾았습니다! Leigh Kaszick의 훌륭한 JavaScript Tutorial : "객체 지향 JavaScript의 기초"덕분에. 그것을 확인하십시오 : http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/

리터럴 객체는 항상 기능적이지 않은 동안 참조됩니다;) 그건 속임수입니다.

리터럴 대상 :

var Storage = { 
    id:'one', 
    content:'blah' 
}; 

기능 개체 :

function Storage(id,content) = { 
     this.id=id; 
     this.content:content; 
} 
var myStorage = new Storage('one','blah'); 

내 문제를 해결하기 위해 나는 클립 보드에 데이터를 전달할 때마다 저장 개체의 새 인스턴스를 만들었습니다. 그리고 그것은 작동합니다! ;)

+0

기능이없는 Object, 클래스입니다. 클래스 "새" – Yosef