jQuery Parameter an eigene Plugins übergeben

walle_89

Mitglied
Hallo!
Ich habe hier ein kleines Problem mit jQuery, wobei manche Parameter nicht an die Methoden weitergegeben werden ...

index.htm
HTML:
[...]
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="settings.js"></script>
<script type="text/javascript" src="penalty.js"></script>
<script type="text/javascript">
<!--

var object = {
	"background": {"color": color.background, "format": format.background},
	"goal":	{"color": color.goal, "format": format.goal},
	"goalkeeper": {"color": color.goalkeeper, "format": format.goalkeeper},
	"ball":	{"color": color.ball, "format": format.ball}
};

try {
	$(document).ready(function(){
		$('#field').get(0).init(object);
	});
} catch(exception) {
  $.log(exception);
}

-->
</script>
<body>
<canvas id="field" width="500" height="500"></canvas>
[...]
P.S. Das JSON-Object enhält noch Daten aus settings.js

Meine Überlegung war, dass ich mit get(0) das Object <canvas> hole und gleichzeitig noch das Plugin init() mit dem Parameter object übergebe. Dazu die penalty.js.

penalty.js
HTML:
(function ($) {

$.fn.init = function (object) {
	if (this.getContext) {
		var ctx = this.getContext('2d');
		// Draw all the objects and check if the execution was successful.
		if (!draw(object)) {
			throw new Error("Objects could not be drawn!");
		}
	} else {
		throw new Error("Canvas could not get initialised!");
	}
};

$.log = function (message) {
  if (window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};

})(jQuery);

Bei init() greife ich auf das HTML-Object <canvas> mit this zu und versuche zu prüfen, ob das Object richtig übergeben wurde und ob der Browser HTML5-Canvas überhaupt unterstützt. Ferner, wenn es klappt, wird die draw Methode auf die übergebene Objects angewendet.

Aber dies will überhaupt nicht funktionieren - es wird die Fehlermeldung "Canvas could not get initialised!" ausgegeben und lässt darauf schließen, dass die Referenzen nicht stimmen ... aber was mache ich falsch? Wie macht man das denn richtig? Vielen Dank schonmal!
 
Hi,

versuch mal, das PlugIn ohne get(0) aufzurufen:
Code:
$(document).ready(function(){
  $('#field').init(object);
});

Das get(0) wird stattdessen innerhalb des PlugIns verwendet:
Code:
$.fn.init = function (object) {
  if (this.get(0).getContext) {
    var ctx = this.get(0).getContext('2d');
    // Draw all the objects and check if the execution was successful.
    if (!draw(object)) {
      throw new Error("Objects could not be drawn!");
    }
  } else {
    throw new Error("Canvas could not get initialised!");
  }
};


Ciao
Quaese
 
Jetzt brummt der FireBug:
"this.get is not a function
if (this.get(0).getContext) { "

Anscheinend wird die Referenz trotzdem falsch geliefert - oder sollte ich allgemein das Grundkonzept (=Vorgehensweise) anders gestalten? An sich habe ich mich mit meiner Ausführung an das folgende Tutorial gehalten => die externe JS-Datei wird genauso aufgebaut ... Hmm.. :(
 
Hi,

hier eine Variante, die bei mir funktioniert.
Code:
<html>
<head>
<title>www.tutorials.de</title>
<meta name="author" content="Quaese">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<!--[if IE]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
  <!--
(function($){
  $.fn.myInit = function(options) {
    // Closure - VORSICHT: this entspricht $(this)
    var _this = this;

    // Canvas-Objekt
    var cvs = this.get(0);

    // IE
    if ((!cvs.getContext) && (typeof G_vmlCanvasManager != "undefined"))
      cvs = G_vmlCanvasManager.initElement(cvs);

    // Optionen-Objekt erweitern
    var opts = jQuery.extend(opts, {
      ctx: null,
      h: 300,
      w: 300
      // weitere Default-Optionen
    }, options);

    var init = function(){
      if (cvs.getContext) {
      	cvs.height = opts.h;
        cvs.width = opts.w;
        cvs.style.height = opts.h + "px";
        cvs.style.width = opts.w + "px";
        cvs.style.border = "1px solid #000";

        opts.ctx = cvs.getContext('2d');
        // Draw all the objects and check if the execution was successful.
        /*if (!draw(object)) {
          throw new Error("Objects could not be drawn!");
        }*/
      } else {
        throw new Error("Canvas could not get initialised!");
      }
    };

    // Public:
    this.drawIt = function(color){
      opts.ctx.fillStyle = color; //"#c00";
      opts.ctx.fillRect(10, 20, 100, 60);

      return this;
    };

    this.clear = function(){
      opts.ctx.clearRect(0, 0, opts.w, opts.h);

      return this;
    };

    // Canvas intitialisieren
    init();

    // ToDo: Sonstiger Code

    // Referenz zurückliefern, um die Kette nicht zu unterbrechen
    return this;
  };
})(jQuery);


$(function(){
  oCvs = $('#cvs_id').myInit({
    w: 400,
    h: 200
  });
  // Zeitverzögert aufrufen wg. IE
  window.setTimeout(function(){oCvs.drawIt('#c00');}, 10);
});
 //-->
</script>

</head>
<body>
<button onclick="oCvs.clear().drawIt('#0c0');">drawIt</button>
<canvas id="cvs_id"></canvas>
</body>
</html>

Ciao
Quaese
 
Vielen vielen Dank! Habe zwar jetzt keine Zeit, werde mir das im Laufe des Tages aber ganz genau anschauen. Ich danke dir erstmal!
 
Zurück