星期四, 5月 30, 2013

[Javascript] 透過prototype的方法存取private member

記錄一下先前遇到的事情,
某一天在寫類別的時候,遇到想要用prototype去存取private member的成員,
就偷懶直接把private member改為public member XD,
查了一下Stackflow javascript - accessing private member variables from prototype-defined functions

No, there's no way to do it. That would essentially be scoping in reverse.
Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.
Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.
You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this object, which the prototype methods (along with everything else)will have access to.

function Dog(_dogName){
    var that = this;
    
    var dogname = _dogName || "dog" ;//default setting
  
    that._getName = function(){
       return dogname;
    };
    
    that._setName = function(newName){
         dogname = newName;
    };

};
//use getName to access private member
Dog.prototype.getName = function(){
    return  this._getName();
};
Dog.prototype.setName = function(newName){
    return  this._setName(newName);
};
    
var myDog = new Dog();
console.log("mydog:" + myDog.getName());

var tomDog = new Dog("tom");
console.log("tomDog:" + tomDog.getName());
tomDog.setName("mary");
console.log("tomDog2:" + tomDog.getName());


Fiddle看範例: Go

Reference:
Private Members in JavaScript

星期五, 5月 24, 2013

[jQuery plugins] 超激推 qtip plugin,讓錯誤訊息的位置不會撐爆XD

jquery validate是一個幾乎每個網站都會採用的外掛,
但是常常會因為錯誤訊息讓版面整個錯亂,
最近為了這個問題,找到了qtip2這個外掛,
強力的支援各種jquery plugin的tooptip外掛。

http://craigsworks.com/projects/qtip2/

為了方便使用就支接寫了一個擴充的方法,避免專案太多地方引用重覆的程式碼
原則上只是把範例的程式包起來而已...XD

//移除qtip2
 $.validator.prototype.qtipDestory = function(element){
      if( $(element).valid()){
       $(element).filter(".valid").qtip("destroy"); 
      }
    };
//顯示qtip2
$.validator.prototype.qtip = function(error,element,my,at){
  // Set positioning based on the elements position in the form
  var elem = $(element),  
  corners = ["right center", "bottom left"],
  flipIt = elem.parents("span.right").length > 0;

  if(my == "undefined" && at != "undefined"){
   corners = [my,at];
  }
  
  // Check we have a valid error message
  if(!error.is(":empty")) {
    // Apply the tooltip only if it isn"t valid
    elem.filter(":not(.valid)").qtip({
     overwrite: false,
     content: error,
     position: {
      my: corners[ flipIt ? 0 : 1 ],
      at: corners[ flipIt ? 1 : 0 ],
      viewport: $(window)
     },
     show: {
      event: false,
      ready: true
     },
     hide: false,
     style: {
      classes: "qtip-red" // Make it red... the classic error colour!
     }
    })

    // If we have a tooltip on this element already, just update its content
    .qtip("option", "content.text", error);
  } 
  // If the error is empty, remove the qTip
  else { elem.qtip("destroy"); }
 }

接著就照老樣子在errorPlacement補上一刀
...省略
errorPlacement:function(error,element){  
  $your_validated.qtip(error,element);
},
//驗證成功會把qtip消除
success:$.noop,

有時候你需要手動清除qtip(自已遇到關掉dialog要手動清除qtip)
//別忘了reset
$your_validated.resetForm();
$(".qtip").each(function(){
   $(this).data("qtip").destroy();
})

星期一, 5月 13, 2013

[Eclipse] bitbucket not authorized

先前把flicklinkr的原始碼改放在bitbucket,
今天要checkout的時候遇到not authorized錯誤
原來使用HTTPS將專案拉回的時候,要輸入你bitbucket上的帳號密碼XD

星期四, 5月 09, 2013

[jQuery Plugins] jquery form ajaxsubmit前修正欄位的名稱或值

jquery form是一個很常用的外掛,
能讓我們簡單做到ajax form的效果,
今天有一個需求想要在送出的時候多加一個欄位時該怎麼處理
只要在beforeSubmit的callback event下,
擴充form欄位的array就可以了。

參考stackoverflow
http://stackoverflow.com/questions/247284/modifying-form-values-with-beforesubmit-with-jquery-ajaxsubmit

範例如下

$(form).ajaxSubmit({
       url: apiEndpoint,
       type: "post",
//       data: postData,
       dataType:  "json", 
       beforeSubmit: function(arr, $form, options){
        

       //The array of form data takes the following form: 
       //$.console(arr);
       arr[arr.length] = { name:"draft", value:draft};
}
});

不過在測試multiform/data post的時候似乎不管用,殘念!!

[jQuery API] removeData 一直都拿不掉資料 WTF

今天發生一很怪的bug,想要用removeData移除先前暫存的資料一直移不掉(某些特別的key:user_jmeter-slave1-user1),如果像是簡單一點的ken,jack倒是沒問題。
想說是不是這個key,對$data方法會有bug發生。

結果寫了測試的方法也沒問題!!,範例如下

http://jsfiddle.net/e92s6/2/

但是在 瀏覽器下的console執行js code也不行。

最後發現jquery官方找到了另一條思路的解法(http://jsfiddle.net/rwaldron/AvqeW/9/),
就是再把資料設成null就好了

範例如下:
//清掉資料
$.data("your_key",null)

//判斷資料還存不存在,如果沒存過第一次是會找到undefined!!
var queryUserData = $.data("your_key",null)
if(typeof (queryUserData) == "undefined" || queryUserData == null){
      //做你要幹的事
  //.....
}



星期三, 5月 08, 2013

[Eclispe] 設定utf-8



開發專案前請記得請大家的環境統一設定UTF-8編碼,避免一些中文註解爆了XD
General/WorkSpace/Other: UTF-8


星期三, 4月 24, 2013

[jQuery plugin] 實作Shift + Click多選行為

如果要模擬window shift鍵多選的行為,可以參考以下這篇文章。
Snippet: Shift + Click List Items with jQuery
主要的邏輯是記錄最後一個選擇的項目
$parentNode.delegate("li","click",function(event){
    
    var $currLI = $(this);
   
    if($currLI.hasClass("select_this")){
     
     //unselected
     $.console("[UserList.render] delegate:unselected user");
     
     if(event.shiftKey){
      //just unselected
      $currLI.removeClass("select_this");
     }else{
      //re-locate last selected/unselected
      $currLI.removeClass("select_this");
      $currLI.addClass("last_selected");
      
      $lastSelected.removeClass("last_selected");
      
      //change last selected
      $lastSelected = $currLI;
     }
    }else{
     
     //selected 
     $.console("[UserList.render] delegate:selected user");
    
     //
     // SHIFT + CLICK
     //
     
     var $shiftSelected = [];//record seleted items by shfit key
     if(event.shiftKey){
      
      //shift + click logic 
      if($lastSelected.length > 0){//first click
       
       if($lastSelected == $currLI){
        $.console("[UserList.render] same selection");
        
        return false;
        
       }else{
        
        //detect foward or back
        direction = $currLI.nextAll(".last_selected").length > 0 ? "forward" : "back";
        $.console("[UserList.render] last_selected count:" + $currLI.nextAll(".last_selected").length);
        $.console("[UserList.render] direction:" + direction);
        
        if(direction == "forward"){
         $shiftSelected = $currLI.nextUntil($lastSelected);
        }else{
         //back
         $shiftSelected = $lastSelected.nextUntil($currLI);
        }
        
//        $.console("$shiftSelected:" + $shiftSelected.length);
        $LICollection.removeClass("select_this");//reset pre selected
        
        //final selected items
        $shiftSelected.addClass("select_this");//highlight shift selected
        $lastSelected.addClass("select_this");//highlight last selected
                 $currLI.addClass("select_this");//highlight current selected
                 
       }
       
      }else{
       
       $lastSelected = $currLI;
       $currLI.addClass("select_this last_selected");
      }
      
     }else{
      
      //record last selected
      $lastSelected = $currLI;
      $currLI.addClass("select_this last_selected");
  
     }
     
    }
    
    //for debug
//    $.console("lastselected username:" + $lastSelected.find(".usr_name").html());
    
    if(userlist.selecteEventHandler && typeof(userlist.selecteEventHandler) === "function"){
     userlist.selecteEventHandler($currLI,userlist.getSelectedItems());
    }
   });

星期五, 4月 19, 2013

[jQuery API] append加上fadeIn的效果

今天要遇到想要在append新元素時,加入fadein的效果。
筆記一下..
//userElem為html tag
$(userElem).hide().appendTo($parentNode).fadeIn(1000);

星期日, 4月 14, 2013

[Alfresco] 如何取得webscript的參數

這篇記錄如何從webscript取得QueryString、Path parameter of URL與Post body

QueryString
<url>/people/search/email?filter={email}</url>
function main()
{
   var filter = args["filter"];
}


Path parameter
<url>/person/{userName}</url>
function main()
{
   // Get the user name of the person to get
   var userName = url.extension;
}

Post Body
function main(){
 
//invalid input
if(!json.has("users")){
    status.setCode(status.STATUS_BAD_REQUEST, "The request body format is error.");
    return;
}

var usersIndex ;
var users = json.get("users");//json array
for (usersIndex = 0; usersIndex < users.length(); usersIndex++){
 //Get user val 
 var currentUser = users.get(usersIndex);
    

}

其他補充

url

A host object providing access to the URL (or parts of the URL) that triggered the web script.
context
Alfresco context path, for example /alfresco
serviceContext
Alfresco service context path, for example /alfresco/service
service
Web script path, for example /alfresco/service/blog/search
full
Web script URL, for example /alfresco/service/blog/search?q=tutorial
templateArgs
a map of substituted token values (within the URI path) indexed by token name
args
Web script URL arguments, for example q=tutorial
match
The part of the web script URL that matched the web script URL template
extension
The part of the web script URL that extends beyond the match path (if there is no extension, an empty string is returned)

For example, imagine a web script URL template of
/user/{userid}
and a web script request URL of
/alfresco/service/user/fred?profile=full&format=html
The url root object will respond as follows:
  • url.context => /alfresco
  • url.serviceContext => /alfresco/service
  • url.service => /alfresco/service/user/fred
  • url.full => /alfresco/service/user/fred?profile=full&format=html
  • url.args => profile=full&format=html
  • url.templateArgs['userid'] => fred
  • url.match => /user/
  • url.extension => fred
Reference:
http://wiki.alfresco.com/wiki/Web_Scripts_Examples#URL_Argument_Handling

星期四, 4月 11, 2013

[Java] Filter Url-Pattern 筆記

久久用一下常常會忘記怎麼正確的設定Filter Url-Pattern,
趁著昨天需要用到,筆記一遍。

第一種解法(舊方法):
http://fecbob.pixnet.net/blog/post/38258307-tomcat-default-servlet-%E7%9A%84url-pattern

filter-mapping在web.xml中定義的順序相同。
在web.xml檔中,以下語法用於定義映射:
  1.  以」/’開頭和以」/*」結尾的是用來做路徑映射的。
  2.  以首碼」*.」開頭的是用來做擴展映射的。
  3. 「/」 是用來定義default servlet映射的。
  4.  剩下的都是用來定義詳細映射的。比如: /aa/bb/cc.action


所以,為什麼定義」/*.action」這樣一個看起來很正常的匹配會錯?因為這個匹配即屬於路徑映射,也屬於擴展映射,導致容器無法判斷。

第二種解法:
http://k2java.blogspot.in/2011/04/servlet-filter-mapping-exclude-pattern.html

透過設定init-parm的方式帶入忽略的URL,並透過Regex來處理

Servlet filter mapping exclude pattern

Once you apply a filter to a URL pattern:
<filter-mapping>
    <filter-name>theFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
/*
there's no option in web.xml to exclude a more specific pattern such as: /public/*.

But you can put the exclusion logic in the filter itself:


<filter>
    <filter-name>theFilter</filter-name>
    <filter-class>org.demo.CustomServletFilter</filter-class>
    <init-param>
 <param-name>excludePatterns</param-name>
 <param-value>public/*</param-value>
    </init-param>
</filter>
org.demo.CustomServletFilter excludePatterns public/*

And in the filter code:
public void init(FilterConfig cfg) throws ServletException {
 this.excludePatterns = cfg.getInitParameter("excludePatterns");
 .
 .
 .
}

public void doFilter(ServletRequest request,
           ServletResponse response,
    FilterChain chain) 
 throws IOException, ServletException {
 String url = request.getRequestURL().toString();
 if (matchExcludePatterns(url)) {
     chain.doFilter(request, response);
     return;
 }
 .
 .
 .
}

[Eclispe] eGIT 建立一個repository

建立一個location repo的擷圖,如果要直接丟到Github上的話,請參考這個



星期二, 4月 02, 2013

[Eclipse] 使用eGIT取回Github上面的專案

前言:
由於平常都使用eclispe開發,所以直接安裝git plugin來存取Github的repo是比較方便的,
感覺把一些sample code放在這,比放在blog上好維護多了xd
所以記錄一下如何從github取回專案 :D

前置處理:
1.請先安裝Egit pluign:

Help->Install New Software
EGit - http://download.eclipse.org/egit/updates
記得二個都打勾!!

星期六, 3月 30, 2013

[jQuery plugin] 通知訊息外掛測試

今天試了二個有關訊息通知的外掛,分別是noty跟notify


http://needim.github.com/noty/ (還是github上2012的前十名 :D)
noty的功能比較強大,不過你要怎麼客制化訊息的位置都非常方便。
此外還有queue的功能。


http://redeyeoperations.com/plugins/Notify/
Notify相較之下就比較簡便了,訊息只能秀在最上方,
也沒有queue的功能,如果你有訊息可能會一直出現時,
原本的區塊就會被取代了。


星期一, 3月 25, 2013

[Eclipse] 搜尋取代大量字串

今天需要將一個東西重新命名一下,但整個專案很多地方有引用,需要一個快速取代的方法。
記錄一下eclipse的操作xd,


1.先搜尋要取代的字,指定搜尋範圍






2.接著在搜尋的結果集按右鍵,就可以看到replace all嚕

星期二, 3月 19, 2013

[jQuery] 如何觸發超連結click動作

今天在模擬使用File API下載檔案,需要一個觸發超連結引發下載的動作,筆記一下。
//dom api
document.getElementById('dllink').click(); 
//jquery api
$("#dllink")[0].click();

[Java] Java Javascript/CSS Asset pipeline

將js有效的模組化具有許多維護上的好處,但缺點但js模組多的時候,頁面載入的時間也就愈長,雖然能在產品前將所有的js打包成一份(用linux指令),但感覺流程上並不適用目前的專案。

目前找到pack-tag這個開源軟體,試用過後感覺非常試合導入專案中,不會影響目前Developer的開發,只需替換掉原本的script標籤,並支援javascript minify。

pack-tag

A JSP Taglib for delivering minified, combined and gzip-compressed resources (JavaScript and CSS).

https://github.com/galan/packtag



[jQuery plugin] 不透過submit觸發jquery validation驗證

jquery validation真是不可或缺的好物,每次用往往有很多用法都會忘記。
趁熱筆記一下。
如果想要不透過submit來觸發驗證的話,可以透過.valid()這個方法。
除了整個form全部驗證之外,也可驗證表單內某一要驗證的元件


$("#myform").validate();
$("a.check").click(function() {
    alert("Valid: " + $("#myform").valid());
    return false;
});

Reference: How do I use jQuery Validate directly, without the submit button?

其他你感興趣的文章

Related Posts with Thumbnails