blog.sowatchasayin

Rails etc.

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

live with no boundaries

jQueryでは.bind()でイベントハンドラを登録できます。
Ajax Requestで帰ってきたエレメントにもイベントハンドラをくっつけてあげたいので、.ready()以外にもajaxCompleteでglobalなcallbackをつけてあげました。

function init(){
bindEvent1(); //色々bindしている
bindEvent2();
bindEvent3();
};
$(document).ajaxComplete(init);
$(init);

すると、Ajax Requestごとに、イベントハンドラが増えるじゃないですか。

調べてみると、.live()ってメソッドで重複なしのイベントハンドラ登録ができるみたい。.bind()から.live()に書き換えたら、無事重複は無くなりました。


Global callback for Ajax calls in JQuery

.live()はこちらで発見

.live() – jQuery API
Ajax Events
Ajax callbackについてはこちら。

ちなみにprototype.jsで同じ事をやるならこうかしら

function init(){
bindEvent1();
bindEvent2();
bindEvent3();
};
window.onload = init;
Ajax.Responders.register({
onComplete: init
});

ArrayのjQuery的な挙動をRubyで

あの勝手にmapしてくれる感じをRubyでも…。適当、かつ冗談です。


module Jq
def method_missing(method_name, *args)
self.map{|a|a.send(method_name, *args)}.flatten
end
end

class Array
include Jq
end


こういうことができます

User.all.articles.comments.body
=> [コメント本文全部]

javascriptを用い、ランダムに画像を表示せよ。連続して同じ画像を表示してはならない。

でけた♪でけた♪

images = ["back1.JPG","back2.JPG","back3.JPG","back4.JPG","back5.JPG"]
rand = function(i){return Math.floor( Math.random() * i );}
setRandomImage = function(){
function another_image(){
r = ("url(" + images[rand(images.length)] + ")");
return document.getElementById("どこか").style.backgroundImage != r ? r : another_image();
};
document.getElementById("どこか").style.backgroundImage = another_image();
};

これをonMouseOverとかで読んであげよう。
サンプル http://so-wat-cha-say.in/
documentオブジェクトに毎回アクセスしてるけど、いいんだ。

Author

Fujimura Daisuke
http://fujimuradaisuke.com

Labels