Archive for the ‘JS’ Category

JSでnewするときにOR(|)が使えるの?

水曜日, 2月 22nd, 2012

お疲れ様です。
new (window.XDomainRequest || window.ActiveXObject || XMLHttpRequest)(‘Microsoft.XMLHTTP’);
ってやり方を見たので、
また、ちょっと、試したいなぁ、という意思表明。
いや、そんなに時間がかかるもんでもないけど、メモのため。

んでやってみた

function test(a){
    this.a = a;
}

test.prototype.bell = function(){
    return this.a;
};


var b = new (unko || test)(45);

console.log(b);

ってやると
[ Uncaught ReferenceError: unko is not defined ]
ってなる
まぁ、そりゃunkoっ変数でも関数でもなければ、なんじゃ、って話っすよね…

var b = new (window.unko || window.test)(45);

ってすると、まぁ、いけるわけすよ。
グローバルのプロパティとして登録されてるかどうか、ってことなので。
window.unko は登録されてないからundefinedとなって、window.testがnewされると。
はぁん、なるほどねぇ。

jsのnamespace

火曜日, 2月 14th, 2012
(function(window,namespace,undefined){
   
    if(!window[namespace]){
        window[namespace] = G;
    }else{
        throw new Error("this namespace [" + namespace + "] is already defined.");
    }
   
   
    function G(a){
        this.message = a || "write somthing";
    }
   
   
    G.prototype.show = function(){
        alert(this.message);
    };
   
    G.prototype.unko = function(){
        alert(this.message + ' unko');
    };
   
}(this,'GAINA'));

var a = new GAINA();
var b = new GAINA("unkokoko");
a.show();   //write somthing
b.show(); //unkokoko

みたいのではダメなのかなぁ…

namespaceも使えるやつだけぶっこんで確かめたりするのかなぁ…

うーん…

if(!namespaceCreate){
    var namespaceCreate = {};
}

function namespaceCreate(global,namespace,classname){
    this.global = global;
    this.namespace = namespace;
    this.classname = classname;
    this.ns = "";
}

namespaceCreate.prototype.create = function(){
    if(this.namespace instanceof Array){
        var len = this.namespace.length,i;
        for(i = 0;i < len; i +=1){
            if(!this.global[this.namespace[i]]){
                this.global[this.namespace[i]] = this.classname;
                this.ns = this.namespace[i];
                return;
            }
            if(i === len - 1){
                throw new Error('these namespace is already defined.');
            }
        }
    }else{
        if(!this.global[this.namespace]){
            this.global[this.namespace] = this.classname;
            this.ns = this.namespace;
        }else{
            throw new Error('this namespace [' + this.namespace + '] is already defined.');
        }
    }
};

namespaceCreate.prototype.debug = function(){
    if(window.console){
        console.log('使用するnamespaceは [' + this.ns + '] です');
    }else{
        alert('使用するnamespaceは [' + this.ns + '] です');
    }
};

(function(window,namespace,undefined){
   
    var ns = new namespaceCreate(window,namespace,G);
    ns.create();
    ns.debug();
    //namespaceCreate(window,namespace,G);
   
    function G(a){
        this.message = a || "write somthing";
    }
   
    G.prototype.show = function(){
        alert(this.message);
    };
   
    G.prototype.unko = function(){
        alert(this.message + ' unko');
    };
   
}(this,['location','window','GAINA']));

var a = new GAINA();
var b = new GAINA("unkokoko");
a.show(); // write somthing
b.show(); // unkokoko

そもそもnamespaceってこんな認識であってるのかもわかんないわー

うだうだやって、最終型

/* ---------------
*
* 名前空間生成
* @class グローバルに色々ぶっこみたいけど名前空間汚しなくないクラス
* @param {window} global
* @param {String} namespace
*
--------------- */


if(!GNamespace){
    var GNamespace = {};
}

function GNamespace(global,namespace){
    if(typeof(namespace) !== 'string'){
        throw new Error();
    }
    var global = global,
    namespace = namespace || 'GNameSpaceObject',
    func = [],
    classname = [],
    ns = "",
    container = global,
    count = 0;
   
    this.namespace = namespace;
   
    return {
        /**
        * 名前空間に追加したい関数をぶっこむ
        * @param {Function} funct 関数でもクラスもどきでも
        * @return this 本体
        */

        add:function(funct){
            func.push(funct);
            // 名前は関数を文字列化してゴニョゴニョして取得
            classname.push(funct.toString().replace(/(function\s)(\w*)(\([\w\s\(\)\{\}\[\]\.\-\_\@\|\&\$\*\=\"\'\\\;\?]*)/,'$2'));
            count += 1;
            return this;
        },
        /**
        * ぶっこまれた関数たちを名前空間に登録する
        * @return this 本体
        */

        register:function(){
            // "gaina-laboratory"のように[-]繋ぎで一単語の場合、
            // 別オブジェクト(gainaとlaboratory)にされちゃうのでアンダーバーに変換する
            namespace = namespace.replace(/-/,'_');
           
            // "com.gaina"のような[.]連結の場合
            if(namespace.split('.').length > 1){
                var n,names = namespace.split('.');
                container = global;
               
                for(n = 0; n < names.length; n += 1){
                    if(typeof(container[names[n]]) === 'undefined'){
                        container[names[n]] = {};
                    }
                    container = container[names[n]];
                }
                var m;
                for(m = 0;m<count;m +=1){
                    container[classname[m]] = func[m];
                }
               
            // 一単語の場合
            }else{
                if(typeof(global[namespace]) === 'undefined'){
                    global[namespace] = {};
                }
                var m;
                for(m = 0;m<count;m +=1){
                    global[namespace][classname[m]] = func[m];
                }
            }
            return this;
        },
        /**
        * 名前空間をコンソールに表示させる
        */

        debug : function(){
            if(window.console){
                console.log('---- namespace ----');
                console.log(namespace);
            }
        }
    };
}

(function(window,namespace,undefined){
   
    var ns = new GNamespace(window,namespace).add(GA).add(G).register().debug();
   
    function GA(){
        this.unko = 'morimori';
    }
   
    GA.prototype.unko = function(){
        alert(this.unko);
    };
   
    function G(a){
        this.message = a || "write somthing";
    }
   
    G.prototype.show = function(){
        alert(this.message);
    };
   
    G.prototype.unko = function(){
        alert(this.message + ' unko');
    };
   
}(this,'com.gaina-laboratory'));



(function(window,namespace,undefined){
   
    var ns = new GNamespace(window,namespace).add(AAA).add(BBB).register().debug();
   
    function BBB(){
        this.unko = 'morimori';
    }
   
    BBB.prototype.unko = function(){
        alert(this.unko);
    };
   
    function AAA(a){
        this.message = a || "write somthing";
    }
   
    AAA.prototype.show = function(){
        alert(this.message);
    };
   
    AAA.prototype.unko = function(){
        alert(this.message + ' unko');
    };
   
}(this,'com.gaina-laboratory.unko'));

console.log(com);

jQueryオブジェクトのcontext

木曜日, 1月 12th, 2012

【メモ】

jQueryオブジェクトのcontextから親を参照するプロパティ

IEやらChromeやらsafariには[parentElement]があるけど

FireFoxには[parentNode]しかないので注意

thisの違い

金曜日, 1月 6th, 2012

当たり前かもしれないけど

var test = {
    test : function(){
        return this;
    }
}

function test02(){
    return this;
}

console.log(test.test()); //Object (test自身)
console.log(test02()); //DOMWindow

underscore

木曜日, 1月 5th, 2012

便利

underscore.js

読み書きプログラミング

ここのやつを写経してた。

anyとかfilterとかtimesとかdelayとかオブジェクト系とか何か色々便利そうだす。

_.filter([1,2,3,4,5,6,7,8,9],function(num){return num % 3 === 0;});

なら、返す値は[3,6,9]

 

mixinで拡張もできる

_.mixin({
    test : function(state){
        console.log("mixin : " + state);
    }
});
_.test("unko"); //mixin : unko

ほへぇ…

コンソール見て

スマートフォンのtouchendのpageX

水曜日, 12月 28th, 2011

あーーーー

JavaScript

jQuery(function($){
    var t = $("#test"),s = $("#start"),m = $("#move"),e = $("#end");
   
    t.on("touchstart",touchStartEvent);
    t.on("touchmove",touchMoveEvent);
    t.on("touchend",touchEndEvents);
   
    s.html("start : " + 0);
    m.html("move : " + 0);
    e.html("end : " + 0);
   
    function touchStartEvent(evt){
        evt.preventDefault();
        s.html("start : " + evt.originalEvent.touches[0].pageX);
    }
   
    function touchMoveEvent(evt){
        evt.preventDefault();
        m.html("move : " + evt.originalEvent.touches[0].pageX);
    }
   
    function touchEndEvents(evt){
        evt.preventDefault();
        e.html("end : " + evt.originalEvent.touches[0].pageX);
    }
});

html

<div id="test" style="background:#CCC;padding:200px 0;">
<h1 style="text-align:center;">touch me</h1>
</div>
<p id="start"></p>
<p id="move"></p>
<p id="end"></p>

[touchend]だけ、数値が取れてない…

[touchend]のプロパティ見たら…pageXは「0」!

ゴニョゴニョとプロパティ値を探っていくと、[changedTouches]のlengthが「1」ってなってなってたから、中身を見てみると、あった、あったよ!pageX!

ってことで

JavaScript修正

jQuery(function($){
    var t = $("#test"),s = $("#start"),m = $("#move"),e = $("#end");
   
    t.on("touchstart",touchStartEvent);
    t.on("touchmove",touchMoveEvent);
    t.on("touchend",touchEndEvents);
   
    s.html("start : " + 0);
    m.html("move : " + 0);
    e.html("end : " + 0);
   
    function touchStartEvent(evt){
        evt.preventDefault();
        s.html("start : " + evt.originalEvent.touches[0].pageX);
    }
   
    function touchMoveEvent(evt){
        evt.preventDefault();
        m.html("move : " + evt.originalEvent.touches[0].pageX);
    }
   
    function touchEndEvents(evt){
        evt.preventDefault();
        e.html("end : " + evt.originalEvent.changedTouches[0].pageX); //ここを修正したのです。
    }
});

ああ、取れてる…ってことでした~

ちなみにjQueryなしの場合は

window.onload = function(){
    var d = document,
    t = d.getElementById("test"),
    s = d.getElementById("start"),
    m = d.getElementById("move"),
    e = d.getElementById("end");
   
    t.addEventListener("touchstart",touchStartEvent,false);
    t.addEventListener("touchmove",touchMoveEvent,false);
    t.addEventListener("touchend",touchEndEvents,false);
   
    s.innerHTML = "start : " + 0;
    m.innerHTML = "move : " + 0;
    e.innerHTML = "end : " + 0;
   
    function touchStartEvent(evt){
        evt.preventDefault();
        s.innerHTML = "start : " + evt.touches[0].pageX;
    }
   
    function touchMoveEvent(evt){
        evt.preventDefault();
        m.innerHTML = "move : " + evt.touches[0].pageX;
    }
   
    function touchEndEvents(evt){
        evt.preventDefault();
        e.innerHTML = "end : " + evt.changedTouches[0].pageX;
    }
};

若干eventの中身が違うのねん~

Iterator

月曜日, 12月 26th, 2011

イテレータってので無限ループするんやみたいな

loopするんじゃね? – jsdo.it – share JavaScript, HTML5 and CSS

スワイプ的なやつ

木曜日, 12月 22nd, 2011

やってみた

//MOUSE ACTIONS
var xx = 0,now = 0,
index,
len = img_arr.length;

$page.on("mousedown",onDowmEvent);
$page.on("mouseup",onUpEvent);

//MOUSE DOWN
function onDowmEvent(evt){
    $page.on("mousemove",onMoveEvent);
    $page.on("mouseleave",onLeaveEvent);
    now = $top.position().left;
    xx = evt.pageX;
    myevent.stop(evt);
}

//MOUSE MOVE
function onMoveEvent(evt){
    $top.stop().animate({
        "left" : now + evt.pageX - xx
    },0);
}

//MOUSE LEAVE
function onLeaveEvent(evt){
    onUpEvent(evt);
}

//MOUSE UP
function onUpEvent(evt){
    $page.off("mousemove",onMoveEvent);
    $page.off("mouseleave",onLeaveEvent);
   
    //NEXT
    if((xx - evt.pageX) > 100){
        if(ite2.current() != ite2.last()){
            ite2.next();
            $top.stop().animate({
                "left" : ite2.current() * -$width
            },300);
        }else{
            $top.stop().animate({
                "left" : now
            },300);
        }
       
    //PREV
    }else if((xx - evt.pageX) < -100){
       
        if(ite2.current() !== ite2.first()){
            ite2.prev();
            $top.stop().animate({
                "left" : ite2.current() * -$width
            },300);
        }else{
            $top.stop().animate({
                "left" : now
            },300);
        }
   
    //NO EXIST NEXT or PREV
    }else{
        $top.stop().animate({
            "left" : now
        },300);
    }
}

[mousedown]で preventDefaul tなり returnValue = false なりをしておかないと、画像をドラッグしちゃう

[mousedown]時のpageX値を格納して、[mousemove]時のpageXとの差分を出して実装

[mousemove]は[mousedown]時に登録[mouseup]で解除する

念のために[mouseleave]を登録しておく

「ite2」って単なる数字の入ったiterator

スワイプ的なやつ

※PCでのスワイプ的なやつってことで

mousewheelメモ

月曜日, 11月 21st, 2011

JSのmousewheelのやつ

window.onload = function(){
   
    if(window.addEventListener){
        window.addEventListener("DOMMouseScroll",scrollEvent,false);
    }
    document.onmousewheel = scrollEvent;
   
    var delta = 0;
   
    function scrollEvent(evt){
        if(!evt){
            evt = window.event;
        }
       
        //1スクロール 12px
        if(evt.wheelDelta){
            delta += evt.wheelDelta / 10;
        }else if(evt.detail){
            delta += evt.detail * -4;
        }
       
        if(evt.preventDefault){
            evt.preventDefault();
        }else{ 
            evt.returnValue = false;
        }
    }
}

だとさ

coffeescriptインストール時にしくった

火曜日, 11月 8th, 2011

coffeescriptが流行ってるらしいのでさくらVPSにぶっこんでみた

npm install coffee-script

を叩いて、test.coffeeつくって

coffee test.coffee

とやると「coffeeなんてコマンドねぇぞ!」って言われる

nvmでnode.jsを管理しているから?ということで

npm install -g coffee-script

でインスコしたらでけた

そんだけっす。