September 10, 2013

Using Anonymous functions in php 5.2

Raj’s Question:

I know Anonymous functions are supported only in php5.3 and above.

But due to some difficult circumstances , I have to use the code below in php 5.2

Can anybody please help me to convert this to work in php 5.2

====================================================

       $fn = function($points) use ($pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);
    };

====================================================

The full code is available at

http://barcode-coder.com/download/php-barcode-2.0.3.zip

I have now tried for hours with create_function but somehow can get this to work.

Please help me to adapt this to php5.2

Also how to duplicate the functionality of use in php5.2

ie how to pass a var like $pdf to create_function

Just sent the variable as parameter:

function fn($points, $pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);
};
June 29, 2012

Confuse about javascript callback function

Question by hh54188

I write two function, which callback will be invoke by the fn:

var callback = function (num) {
        return num + 1;    
}
var fn = function (callback) {
    callback();
}

fn(callback(5));

the firebug tell me: number is not a function ,I know the callback is execute immediately, how can I let it execute in the fn return the num in the fn function, the fn function is only allow the callback parameter

Answer by Elias Van Ootegem

Your example is a not great, seeing as there is no actual need for a second function. But this is what I’d do all the same:

function makeCallback(num)
{
    return function()
    {
        return num+1;
    }
}

fn = function (callback)
{
    callback.apply(this);
}

Seeing that a callback is generally called in an object context (DOM elements, when an event is handled etc) You might want to call the callback function, you passed as an argument to be called in the objects’ context.

Closures are a bit daunting and hard to fathom at first, but there are some great videos with Douglas Crockford on youtube on the matter, that really explain their workings well

Answer by Starx

It is happening due the parameter naming. The way you are using the parameters, makes a call to function called 6() which ends up being incorrect.

So, Use the following (IMO, this is what you are attempting)

var callback = function (num) {
        return num + 1;    
}
var fn = function (num) {
    callback(num);
}

fn(callback(5));

Demo

And so far for the attempt of your to create a callback function. You are only missing a return statement in the function see the result.

var callback = function (num) {
        return function(){
                return num + 1;
        };    
}
var fn = function (callback) {
    return callback();
}

console.log(fn(callback(5)));

Demo

April 5, 2012

How to add a callback for setAttribute?

Question by Steffi

Is it possible to add a callback on setAttribute on Prototype ?

For this example, I would like to show an alert("done !") when setAttribute() is finished.

img.setAttribute("src", "http://blabla.com/c.jpg");

Answer by alex

You could, but I wouldn’t recommend it.

(function() {

    var elementSetAttribute = Element.prototype.setAttribute;

    Element.prototype.setAttribute = function() {
        whateverFunctionYouWant.call(this);

        return elementSetAttribute.apply(this, arguments);
    }

})();

jsFiddle.

This will call whateverFunctionYouWant() when you do something such as document.links[0].setAttribute('href', '/').

You seem to want this to call a callback when you change the src attribute of img elements and the new resource has loaded…

(function() {

    var HTMLImageElementSetAttribute = HTMLImageElement.prototype.setAttribute;

    HTMLImageElement.prototype.setAttribute = function(attribute, value) {
        var image;

        if (attribute == 'src') {
            image = new Image;
            image.addEventListener('load', loaded, false);
            image.src = value;
        }

        return HTMLImageElementSetAttribute.apply(this, arguments);
    }

})();

jsFiddle.

You could overload setAttribute() here with a third parameter, which would be the callback.

In my opinion and experience, I’d create a different function instead for doing this. Modifying prototypes is one thing, but overloading native DOM methods to do extra things sounds like inviting trouble, especially once a developer unfamiliar with what you’ve done looks at the code.

It goes without saying that if you want the latter example to work < IE9, use the attachEvent() fallback for adding the event listener.

Answer by Starx

May be not the golden solution but

img.setAttribute("src", "http://blabla.com/c.jpg");
img.onload = imageCallback;

function imageCallback() { ... }

If you are interested in jQuery, there is plugin called waitforimages that might help.

March 25, 2012

PrettyPhoto – passing unique parameter from iframe window to parent page

Question by Gublooo

I’ve recently started using prettyphoto to display a video.

This is my current setup

<link rel="stylesheet" href="/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="/js/jquery.prettyPhoto2.js" type="text/javascript" charset="utf-8">

<script type="text/javascript" charset="utf-8">
  $(document).ready(function(){
    var lastClicked = null;
    $("a[rel^='prettyPhoto']").prettyPhoto({
    callback: function()
    {           
        if(lastClicked != null) {
                var topicid = lastClicked.data("topicid"); 
                $.post('/course/close-video', {topic_id: topicid });
                lastClicked = null;
        }
    }
    }).click(function (){
        lastClicked = $(this);
});
</script>


<a data-topicid="<?php echo $topic->topic_id;?>" href="/course/play-video/topic_id/<?php echo $topic->topic_id;?>?iframe=true&width=470&height=340" rel="prettyPhoto" title="<?php echo $topic->topic_name;?>">
<img src="/images/videos/<?php echo $image_name;?>" width="170" height="103" alt="<?php echo $topic->topic_name;?>"/>
</a>

This is what is happening

1) When a user clicks on the link – the play-video php action is called which retrives the video url from database and passes so that it can be played on the popup window. This works fine.

2) Now the play-video also generates a unique id which is passed on to the page (iframe window) where the video is played. Right now I’m just displaying that value on the page. I can have that unique id stored as a hidden field or as a div value.

3) Now when the user closes this window – how can I access this unique id in the callback function of pretty photo which is in the main page.

Thanks a lot
Appreciate your time

Answer by Starx

Create a variable on the main page.

var UniqueId; //Unique ID that will arrive from the iframe

Now a function to write the value

function setUniqeId(val) {
    UniqueId = val;
}

Now inside the iframe, where the id, has already been receive, pass it to the parent like

parent.setUniqueId(TheIdThatIHaveReceived);

Update:

Make sure the script to read is after the DOM is loaded. One of the early ways of ensuring this, is placing the script after the Elements

<input id="topic_user_id" type="text" />
<script>
var unique_id = document.getElementById("topic_user_id").value;
parent.setUniqueId(unique_id);
</script>

One of the modern techniques would be to create a event handler like

window.onload = function() {
    var unique_id = document.getElementById("topic_user_id").value;
    parent.setUniqueId(unique_id);
};
March 5, 2012

jQuery Animation Conditional w/a Callback Function

Question by Andaero

EDIT BELLOW

How do I code the #west animation call on the #contentBox animation when it completes?

Basically I have a toggle button that animates/changes a div’s css and then to another div’s css once/after the first animation completes; then reverses the next time the toggle is executed.

Any help is appreciated. Thank-you.

The Conditional Statements:

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        });

        $west.animate({
            left : parseInt($west
                .css("left"), 10) == 0 
                ? -$west.outerWidth() 
                : 0
        });
   });

I went to the old fashoned way with out shorthanding the conditional statement

Answer by Andaero

I re-wrote the statement so it wasnt in shorthand and it works fine.

$("#menuToggle").click(

        function() {
            //var n = $("#west");
            var position = $("#west").offset();

            if (position.left == "0") {
                $("#west").animate({"left" : "-=300px"}, "slow")
                .animate({"width" : "1%"}, "fast", 
                    function() {
                    $("#contentBox").animate({"width" : "98%"}, "normal");
                });
            } else {
                $("#contentBox").animate({"width" : "70%"}, "normal", 
                    function() {
                    $("#west").animate({"width" : "30%"}, "fast")
                    .animate({"left" : "+=300px"}, "slow");
                });
            }
        });

Answer by Starx

You can always pass a callback function to the animate() method, which execuies once the animation is complete.

$("#menuToggle").click(
    function() {

        var $west = $("#west");
        var $contentBox = $("#contentBox");

        $contentBox.animate({
                marginLeft : parseInt($contentBox
                        .css('marginLeft'), 10) == -320
                        ? $contentBox.outerWidth()
                        : -320
        }, 5000, function() {
             //this is the callback part
            $west.animate({
                left : parseInt($west
                    .css("left"), 10) == 0 
                    ? -$west.outerWidth() 
                    : 0
            });
        });

   });
March 2, 2012

jquery function that load html code into a div and then load other content into div inside html loaded

Question by Raphael D.G

I’d like to know what’s the way to load an html page (page1.html) into a div in webpage active (index.html) and then load another html page (page2.html) into a div that will be inside of page loaded (page1.html). I mean.

index.html

<div id="content"></div>
<a class="link" href="#">load</a>

script

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('#content').load('page1.html', function(){
            $('#content2').load('page2.html');
        });
    });
});

page1.html

<div id="content2"></div>

It’s works fine for only 1 click, at the second click it loads page2.html for 0,5 seconds and then loads page1.html.

What’s the problem ???

Thank you

Answer by Starx

If I am correct, you are trying to load onto the second secontainer, after first container is loaded

Add a simple class on your markup

<div id="content" class="toload"></div>

&

<div id="content2" class="toload"></div>

Now, here is the magical jQuery you need

$(document).ready(function() {
    $('a.link').live('click', function() {
        $('.toload').load('page1.html', function(){
            $(this).removeClass('toload');  //Remove the class so that next time it does not get affected
        });
    });
});
...

Please fill the form - I will response as fast as I can!